// utils/navigation-history.js - 导航历史管理工具

/**
 * 添加跳转历史记录
 * @param {string} fromPageType - 来源页面类型 ('product-detail' | 'cart')
 * @param {string} toPageType - 目标页面类型 ('product-detail' | 'cart')
 * @param {string} productId - 商品ID（如果是商品详情页）
 */
function addNavigationRecord(fromPageType, toPageType, productId = null) {
  const app = getApp();
  let jumpHistory = app.globalData.jumpHistory || [];

  // 创建新的跳转记录
  const newRecord = {
    fromPageType,
    toPageType,
    productId,
    timestamp: Date.now(),
  };

  // 添加到历史记录
  jumpHistory.push(newRecord);

  // 限制历史记录最多保存6条（3个完整的来回跳转）
  if (jumpHistory.length > 6) {
    jumpHistory = jumpHistory.slice(-6);
  }

  app.globalData.jumpHistory = jumpHistory;

  // 通知TabBar更新（延迟执行，确保页面跳转完成）
  setTimeout(() => {
    app.updateCustomTabBar();
  }, 100);

  console.log("添加跳转记录:", newRecord);
  console.log("当前历史记录:", jumpHistory);

  return jumpHistory;
}

/**
 * 获取最后一个跳转记录
 * @returns {Object|null} 最后一个跳转记录
 */
function getLastNavigationRecord() {
  const app = getApp();
  const jumpHistory = app.globalData.jumpHistory || [];
  return jumpHistory.length > 0 ? jumpHistory[jumpHistory.length - 1] : null;
}

/**
 * 移除最后一个跳转记录
 * @returns {Object|null} 被移除的记录
 */
function removeLastNavigationRecord() {
  const app = getApp();
  const jumpHistory = app.globalData.jumpHistory || [];

  if (jumpHistory.length > 0) {
    const removedRecord = jumpHistory.pop();
    app.globalData.jumpHistory = jumpHistory;

    // 通知TabBar更新（延迟执行，确保页面跳转完成）
    setTimeout(() => {
      app.updateCustomTabBar();
    }, 100);

    console.log("移除跳转记录:", removedRecord);
    console.log("剩余历史记录:", jumpHistory);

    return removedRecord;
  }

  return null;
}

/**
 * 清空所有跳转历史记录
 */
function clearNavigationHistory() {
  const app = getApp();
  app.globalData.jumpHistory = [];
  console.log("清空跳转历史记录");
}

/**
 * 检查是否有跳转历史记录
 * @returns {boolean} 是否有历史记录
 */
function hasNavigationHistory() {
  const app = getApp();
  const jumpHistory = app.globalData.jumpHistory || [];
  return jumpHistory.length > 0;
}

/**
 * 从商品详情跳转到购物车
 * @param {string} productId - 商品ID
 */
function navigateFromProductDetailToCart(productId) {
  addNavigationRecord("product-detail", "cart", productId);

  wx.switchTab({
    url: "/pages/cart/cart",
  });
}

/**
 * 从购物车跳转到商品详情
 * @param {string} productId - 商品ID
 */
function navigateFromCartToProductDetail(productId) {
  addNavigationRecord("cart", "product-detail", productId);

  wx.navigateTo({
    url: `/pages/product-detail/product-detail?productId=${productId}`,
  });
}

/**
 * 返回上一个页面
 * @returns {boolean} 是否成功返回
 */
function navigateBack() {
  const lastRecord = removeLastNavigationRecord();

  if (lastRecord) {
    if (lastRecord.fromPageType === "product-detail") {
      wx.navigateTo({
        url: `/pages/product-detail/product-detail?productId=${lastRecord.productId}`,
      });
    } else if (lastRecord.fromPageType === "cart") {
      wx.switchTab({
        url: "/pages/cart/cart",
      });
    }
    return true;
  }

  return false;
}

module.exports = {
  addNavigationRecord,
  getLastNavigationRecord,
  removeLastNavigationRecord,
  clearNavigationHistory,
  hasNavigationHistory,
  navigateFromProductDetailToCart,
  navigateFromCartToProductDetail,
  navigateBack,
};
